package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        // 1. 校验参数  分页   是否登陆
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 封装查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        // 2.1 标题
//        if(StringUtils.isNotBlank(dto.getKeyword())){
//            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
//        }
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //2.2频道id查询
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //2.3状态信息查询
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //2.4开始时间和结束时间查询
        queryWrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                WmNews::getCreatedTime,
                dto.getBeginPubDate(),
                dto.getEndPubDate());
        // //2.5登录用户id查询
        queryWrapper.eq(WmNews::getUserId, user.getId());
        // 2.6 设置创建时间降序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        // 3. 封装分页条件
        Page<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 4. 执行查询
        IPage<WmNews> pageResult = this.page(pageReq, queryWrapper);
        // 5. 返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                pageResult.getTotal(), pageResult.getRecords());
        // 设置图片前缀路径
        result.setHost(webSite);
        return result;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1 检查参数  封装WmNews对象
        WmNews wmNews = parseDtoToWmNews(dto);
        //2 保存或修改文章
        saveOrUpdateWmNews(wmNews);


        //3 保存文章内容 或 封面 和素材的关联关系
           //   3.1 todo 从文章内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
           //   3.2 todo 保存文章内容 引用素材的关联联系
        saveRelativeInfo(materialUrls,wmNews,WemediaConstants.WM_CONTENT_REFERENCE);
           //   3.3 todo 保存封面 引用素材的关联联系
        saveRelativeInfoForCover(materialUrls,wmNews,dto);

        return ResponseResult.okResult();
    }

    //根据文章id查询文章
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    //删除文章
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.根据文章获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();

    }


    //上下架
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章当前的状态是否为9,9是已发布的状态
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            //如果没有发布就不能调整上下架
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.如果已经发布,修改文章状态，同步到app端（后期做） TODO
        //eq(WmNews::getId,dto.getId()) 修改的条件(本质是修改状态)
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));//set修改那个字段(Enable)
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面 引用素材的关联联系
     * @param materialUrls
     * @param wmNews
     * @param dto
     * images 封面
     */
    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {
        //封面集合(前端传过来的封面,有前缀,要处理):最后几行代码解决
        List<String> images = dto.getImages();

        //              判断前端传入type是否为-1(WM_NEWS_TYPE_AUTO)
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 需要自动生成封面  规则
            int size = materialUrls.size();
            if (size == 0) {
                // -内容中没有图片  则为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                //从素材截取去一张图片,赋值给 images
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                //-内容图片的个数小于等于2  则为单图截图一张图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size <= 3) {
                //从素材截取去三张图片,赋值给 images
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                //   -内容图片的个数大于2  则为多图,截图三张图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }

            //如果集合不为空,把封面设置一下
            if (!CollectionUtils.isEmpty(images)){
                //转成字符串,设置到封面字段上
                wmNews.setImages(imagesToStr(images));
            }
            //修改文章
            this.updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)) {
            //替换前缀(解决第一行的问题)
            images = images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());

            // 调用保存关联关系方法
            //            封面信息   文章信息  引用类型(封面)
            saveRelativeInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
        }




    }




    /**
     * 保存素材和关联关系的方法
     * @param materialUrls 素材的路径List
     * @param wmNews 文章
     * @param type 引用类型 0 内容引用  1 封面引用
     */
    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        //1 现根据素材路径集合 查询素材表 得到对应的id集合
        /*List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .in(WmMaterial::getUrl, materialUrls)
                        //只返回id字段的值
                        .select(WmMaterial::getId)
        );*/

        //TODO ids集合(上面5行太复杂,用xml文件改写)
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());


        //2 判断id集合的数量 是否等于 素材路径集合的数量 不等于提示素材缺失
        if (ids.size() < materialUrls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失");
        }
        //3 批量的插入关联关系
       /* for (WmMaterial wmMaterial : wmMaterials) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(wmMaterial.getId());
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);

        }*/


        /*
         *   TODO 上面5行太复杂,利用Foreach标签实现的批量保存的方法
         *    (多个失去了语句合成一个执行,减少和数据库的交互,提升性能)
         *                           素材id /文章id / 类型传进去
         */
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),type);

    }







    private List<String> parseContentImages(String content){
        List<Map> mapList = JSON.parseArray(content, Map.class);
        return mapList.stream() //创建流
                //集合中 找到所有的type 为image 的map
                .filter(x -> "image".equals(x.get("type")))
                //获取map的value字段值 得到路径
                .map(x -> String.valueOf(x.get("value")))//得到的value转成字符串
                //替换掉路径的前缀
                .map(url -> url.replaceAll(webSite,""))
                //去除重复的素材
                .distinct()
                //将得到的素材返回路径集合
                .collect(Collectors.toList());
    }



    private void saveOrUpdateWmNews(WmNews wmNews) {
        //   2.1 wmNews信息补全(创建时间 上下架  发表用户id)
        wmNews.setCreatedTime(new Date());
             //文章状态 9
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);

        //   2.2 判断id是否为空, 为空保存images
        if (wmNews.getId()==null) {
            this.save(wmNews);
        }else{
            //   2.3如果不为空 修改wmNews 修改前先将 文章和素材的关联关系删去
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);
        }


    }


    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        //   1.1 检查标题 内容  是否登录
        if (StringUtils.isBlank(dto.getTitle())||StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章的标题和内容不过不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //   1.2 dto拷贝属性 WmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //   1.3 type: 如果type为-1 暂时将WmNews中的type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //   1.4 dto中的images是list  wmNews的images是字符串
        if (CollectionUtils.isEmpty(dto.getImages())){
            String images = imagesToStr(dto.getImages());
        }
        return wmNews;
    }

    /**
     * 将字符串集合 转为 字符串用逗号拼接
     * @param images [url1.jpg, url2.jpg]
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream() //创建流对象
                //替换路径中的访问路径前缀
                .map(url -> url.replaceAll(webSite,""))//去掉前缀
                //将字符串用头号拼接
                .collect(Collectors.joining(","));
    }


}

